import { fileList, addFile, deleteFile } from '@/api/user'
import moment from 'moment'

const state = {
  // 文件列表
  fileList: [],
  // 是否显示文件上传框
  ifShowDialog: false,
  // 弹框需要展示的内容
  dialogData: {},
  // 文件列表
  filePage: [],
  // 当前页
  currentPage: 1,
  // 总文件数
  total: +'',
  // 文件列表查询字符
  searchWord: ''
}

const mutations = {
  // 设置文件列表
  set_fileList (state, list) {
    state.fileList = list
  },
  // 设置是否展示文件上传框
  set_ifShowDialog (state, bool) {
    state.ifShowDialog = bool
  },
  // 设置弹框需要展示的内容
  set_dialogData (state, obj) {
    state.dialogData = obj
  },
  // 设置当前页
  set_currentPage (state, page) {
    state.currentPage = page
  },
  // 设置总文件数
  set_total (state, total) {
    state.total = total
  },
  // 设置文件列表查询字符
  set_searchWord (state, str) {
    state.searchWord = str
  }
}

const actions = {
  // 获取文件列表
  getFileList ({ state, commit }, pageSize) {
    if (!pageSize) {
      pageSize = 12
    }
    return new Promise((resolve, reject) => {
      // const searchWord = encodeURI(state.searchWord)
      const searchWord = state.searchWord
      fileList(searchWord, state.currentPage, pageSize).then(res => {
        if (res.data.data && res.data.data.data) {
          res.data.data.data.forEach(item => {
            item.file_name = decodeURI(item.file_name)
            item.add_time = moment(new Date(+new Date(item.add_time) - new Date().getTimezoneOffset() * 60000)).format('YYYY-MM-DD HH:mm:ss')
          })
        }
        commit('set_fileList', res.data.data.data || [])
        commit('set_total', res.data.data.total)
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 添加文件
  addFiles ({ commit, dispatch }, fileID) {
    return new Promise((resolve, reject) => {
      addFile(fileID).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 删除文件
  fileDelete (context, fileID) {
    return new Promise((resolve, reject) => {
      deleteFile(fileID).then(res => {
        resolve(res)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
